<template>
     <el-card >
   <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/basicdata' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <a href="/basicdata">库存管理</a>
    </el-breadcrumb-item>
    <el-breadcrumb-item>库存盘点</el-breadcrumb-item>
  </el-breadcrumb>

  <br>
  <br>

<div style="border: 1px solid #ccc;margin: 10px;padding: 10px;">

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="盘点单号：">
      <el-input v-model="formInline.StandingBookOod" placeholder="调拨单号" clearable style="width: 200px;"/>
    </el-form-item>

    <el-form-item label="盘点类型：">
      <el-select v-model="formInline.StandingBookType" placeholder="请选择" class="full-width" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option label="初期盘点" value="初期盘点" />
                <el-option label="存货盘点" value="存货盘点" />
                <el-option label="期末盘点" value="期末盘点" />
              </el-select>
    </el-form-item>

    <el-form-item label="仓库名称：">
      <el-select v-model="formInline.WarehouseId" placeholder="请选择" class="flex-grow" style="width: 200px;">
                  <el-option label="请选择" value="" />
                  <el-option v-for="s in xialawarehouse" :label="s.warehousename" :value="s.warehouseid" />
                </el-select>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="Seach">查询</el-button>
      <el-button type="primary" @click="OutForm">重置</el-button>
      <el-button type="primary" @click="dialogFormVisible = true">添加</el-button>
    </el-form-item>
  </el-form>
</div>

    </el-card>
    <br>
    
    <el-card>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="80" />
    <el-table-column prop="standingBookOod" label="盘点单号" width="120" />
    <el-table-column prop="standingresult" label="盘点结果" width="120" />
    <el-table-column prop="warehouseId" label="仓库名称" width="120" />
    <el-table-column prop="standingBookType" label="盘点类型" width="120" />
    <el-table-column prop="standingBookOpenDate" label="盘点开始时间" width="100" />
    <el-table-column prop="standingBookCloseDate" label="盘点结束时间" width="120" />
    <el-table-column prop="itemId" label="盘点货品" width="120" />
    <el-table-column prop="standingBookNumber" label="盘点数量" width="120" />
    <el-table-column prop="profitNumber" label="盘盈盘亏数量" width="120" />
    <el-table-column prop="profitMoney" label="盘盈盘亏金额" width="120" />
    <el-table-column prop="empid" label="经办人" width="120" />
    <el-table-column prop="empid" label="制单人" width="120" />
    <el-table-column prop="creationTime" label="制单时间" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="DelStanding(scope.row.standingBookOod)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="UpdateStanding(scope.row.standingBookOod)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>

  <table>
    <tr>
        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot,total, sizes"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
当前第{{ y.PageIndex }}/{{ y.totalPage }}
</el-pagination>
        </td>

        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot, prev, pager, next"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
<el-button @click="handleCurrentChange(1)">首页</el-button>
</el-pagination>
        </td>

        <td>
            <el-pagination
      v-model:current-page="y.PageIndex"
      v-model:page-size="y.PageSize"
      :page-sizes="[2, 3, 5, 10]"
      layout="slot, jumper"
      :total="y.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >
    <el-button @click="handleCurrentChange(y.totalPage)">尾页</el-button>
</el-pagination>
        </td>
    </tr>
</table>

<!-- 添加盘点弹出框 -->
<el-dialog v-model="dialogFormVisible" title="添加盘点单" width="1500px">
  <!-- 基础信息部分 -->
  <el-card class="basic-info-card">
    <div class="card-title">基础信息</div>
    <br>
    <el-form :model="formData" label-width="120px" label-position="right">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="盘点单号" required>
            <el-input v-model="formData.standingBookOod" placeholder="自动获取系统编号" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点类型">
            <el-select v-model="formData.standingBookType" placeholder="请选择" class="full-width">
              <el-option label="请选择" value="" />
              <el-option label="初期盘点" value="初期盘点" />
              <el-option label="存货盘点" value="存货盘点" />
              <el-option label="期末盘点" value="期末盘点" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="盘点开始时间" required>
            <el-date-picker
              v-model="formData.standingBookOpenDate"
              type="datetime"
              placeholder="请选择日期时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点结束时间" required>
            <el-date-picker
              v-model="formData.standingBookCloseDate"
              type="datetime"
              placeholder="请选择日期时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库名称" required>
            <div class="flex-container">
              <el-select v-model="formData.warehouseId" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialawarehouse" :key="s.warehouseid" :label="s.warehousename" :value="s.warehouseid" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经办人">
            <div class="flex-container">
              <el-select v-model="formData.empid" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialaus" :key="s.id" :label="s.trueName" :value="s.id" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.standingBookRemark" type="textarea" :rows="3" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <!-- 盘点明细部分 -->
  <el-card class="detail-card">
    <div class="card-header">
      <div class="card-title">盘点明细</div>
      <br>
      <div class="button-group">
        <el-button type="primary" @click="showDetailDialog = true">添加</el-button>
        <el-button @click="removeSelected">移除</el-button>
        <el-button @click="importData">导入</el-button>
      </div>
    </div>
    
    <el-table :data="formData.standingBookSub" style="width: 100%" max-height="400">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="itemName" label="货品名称" width="120" />
      <el-table-column prop="itemId" label="货品编号" width="120" />
      <el-table-column prop="itemSpec" label="规格型号" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="itmeTypeName" label="货品类型" width="120" />
      <el-table-column prop="bookedInventory" label="账面库存" width="120" />
      <el-table-column prop="bookedAmount" label="账面金额" width="120" />
      <el-table-column label="盘点库位" width="120">
        <template #default="scope">
          <el-select v-model="scope.row.storageLocationID" placeholder="请选择" class="flex-grow" style="width: 200px;">
                <el-option label="请选择" value="" />
                <el-option v-for="s in xialaku" :key="s.librarylocationid" :label="s.librarylocationname" :value="s.librarylocationid" />
              </el-select>
        </template>
      </el-table-column>
      <el-table-column label="盘点数量" width="120">
        <template #default="scope">
          <el-input 
            v-model="scope.row.standingBookNumber" 
            placeholder="请输入数量" 
            @input="calculateProfitLoss(scope.row)"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="盈亏数量" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.profitNumber"
            placeholder="请输入盈亏数量"
            @input="calculateProfitMoney(scope.row)"
            style="width: 100%"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" width="120">
        <template #default="scope">
          <el-tag 
            :type="scope.row.profitNumber > 0 ? 'success' : scope.row.profitNumber < 0 ? 'danger' : 'info'"
            size="small"
          >
            {{ scope.row.standingBookType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="参考单价" width="120">
        <template #default="scope">
          <el-input 
            v-model="scope.row.price" 
            placeholder="100" 
            @input="calculateProfitLoss(scope.row)"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="盈亏金额" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.profitMoney > 0 ? '#67C23A' : scope.row.profitMoney < 0 ? '#F56C6C' : '#909399' }">
            {{ scope.row.profitMoney }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.standingBookRemark" placeholder="请输入" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click.prevent="removeSelected(scope.$index)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 合计行 -->
    <div class="summary-row">
     
      <span>盘点数量: {{ totalStocktakingQuantity }}</span>
      <span>盘盈数量: {{ totalProfitQuantity }}</span>
      <span>盘亏数量: {{ totalLossQuantity }}</span>
      <span>盘盈金额: {{ totalProfitAmount }}</span>
      <span>盘亏金额: {{ totalLossAmount }}</span>
    </div>
  </el-card>
  
  <div style="text-align: center; margin-top: 20px;">
    <el-button type="primary" @click="saveStocktaking">保存</el-button>
    <el-button @click="dialogFormVisible = false">取消</el-button>
  </div>
</el-dialog>

<!-- 货品选择弹出框 -->
<el-dialog
  title="选择货品"
  v-model="showDetailDialog"
  width="90%"
>
  <el-table
    :data="itemList"
    @selection-change="handleItemSelection"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="itemid" label="货品编号" width="120" />
    <el-table-column prop="itemname" label="货品名称" width="150" />
    <el-table-column prop="itemspec" label="规格型号" width="120" />
    <el-table-column prop="unitid" label="单位" width="80" />
    <el-table-column prop="itmeTypeName" label="货品类型" width="120" />
    <el-table-column prop="purchaseprice" label="账面库存" width="120" />
    <el-table-column prop="outboundprice" label="账面金额" width="120" />
  </el-table>
  <div style="margin-top: 16px; text-align: right;">
    <el-button @click="showDetailDialog = false">取消</el-button>
    <el-button type="primary" @click="addSelectedItems">确定</el-button>
  </div>
</el-dialog>

</el-card>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref, computed } from 'vue';
import { Warning } from '@element-plus/icons-vue';



const tableData=ref([])

const y=reactive({
    PageIndex:1,
    PageSize:10,
    totalCount:0,
    totalPage:0
})

onMounted(()=>{
    Seach();
    WareHouse();
    fetchItemList();
    xialakuwei();
    xialauser();
})

const xialaus=ref([{
    id:'',
    trueName:''
}])

const xialauser=()=>{
    axios.get("api/app/standing/user").then(res=>{
        xialaus.value=res.data.pageData
    })
}


const xialaku=ref([{
    librarylocationname:'',
    librarylocationid:''
}])
const xialakuwei=()=>{
    axios.get("api/app/location/location-list?pageindex=1&pagesize=100").then(res=>{
        xialaku.value=res.data.pageData
    })
}



const xialawarehouse=ref([{
  warehousename: '',
  warehouseid: ''
}])

const WareHouse=()=>{
  axios.get("api/app/allot/ware-house").then(res=>{
xialawarehouse.value=res.data.data
  })
}


const formInline = reactive({
    StandingBookOod: '',
    StandingBookType: '',
    WarehouseId: '',
})
const OutForm=()=>{
   formInline.StandingBookOod='',
   formInline.StandingBookType= '',
   formInline.WarehouseId= ''
}


const Seach=()=>{
    axios.get("api/app/standing/standing",{params:{
        PageIndex:y.PageIndex,
        PageSize:y.PageSize,
        StandingBookOod:formInline.StandingBookOod,
        StandingBookType:formInline.StandingBookType,
        WarehouseId:formInline.WarehouseId
    }}).then(res=>{
        if(res.data.code==200){
            tableData.value=res.data.pageData
            y.totalCount=res.data.totalCount
            y.totalPage=Math.ceil(y.totalCount/y.PageSize)
        }
    })
}


const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
   y.PageSize=val;
  Seach();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
   y.PageIndex=val;
  Seach();
}

const DelStanding=(standingBookOod:any)=>{
ElMessageBox.confirm(
    '确定要删除吗！！！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
       axios.delete("api/app/standing/stading?StandingBookOod="+standingBookOod,{
  })
  .then(res=>{
      if(res.data.code==200)
      {
          ElMessage.success(res.data.message)
          Seach();
      }
      else
      {
          ElMessage.error(res.data.message)
      }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

// 弹出框控制
const dialogFormVisible = ref(false);
const showDetailDialog = ref(false);
const ysb = ref('');
// 表单数据
const formData = ref({
   "standingBookOod": ysb.value,
  "standingBookType": "",
  "standingBookOpenDate": "",
  "standingBookCloseDate": "",
  "warehouseId": "",
  "empid": "",
  "standingBookRemark": "",
  "standingBookSub": [
    {
      "standingBookOod": ysb.value,
      "itemId": "",
      "storageLocationID": "",
      "standingBookNumber": 0,
      "profitNumber": 0,
      "standingBookType": "",
      "price": 0,
      "profitMoney": 0,
      "standingBookRemark": ""
    }
  ]
});

// 货品列表
const itemList = ref([{
     
}]);
const selectedItems = ref([]);

// 获取货品列表
const fetchItemList = () => {
  axios.get('api/app/allot/item').then(res => {
      itemList.value = res.data.pageData;
  });
};

// 处理货品选择
const handleItemSelection = (val: any) => {
  selectedItems.value = val;
};


// 添加选中的货品到明细
const addSelectedItems = () => {
  const newItems = selectedItems.value.map((item: any) => ({
    standingBookOod: ysb, // 使用当前表单的盘点单号
    itemId: item.itemid,
    itemName: item.itemname,
    itemSpec: item.itemspec,
    unit: item.unitid,
    itmeTypeName: item.itmeTypeName,
    bookedInventory: item.purchaseprice,
    bookedAmount: item.outboundprice,
    storageLocationID: '',
    standingBookNumber: 0,
    profitNumber: 0,
    standingBookType: '无盈亏',
    price: 100,
    profitMoney: 0,
    standingBookRemark: ''
  }));

  // 合并去重
  const ids = new Set(formData.value.standingBookSub.map((i: any) => i.itemId));
  newItems.forEach((item: any) => {
    if (!ids.has(item.itemId)) {
      formData.value.standingBookSub.push(item);
    }
  });

  showDetailDialog.value = false;
  selectedItems.value = [];
};

// 计算盈亏
const calculateProfitLoss = (row: any) => {
  const bookedQuantity = Number(row.bookedInventory) || 0;
  const stocktakingQuantity = Number(row.standingBookNumber) || 0;
  const referencePrice = Number(row.price) || 100;
  
  row.profitNumber = stocktakingQuantity - bookedQuantity;
  row.profitMoney = (row.profitNumber * referencePrice).toFixed(2);
  
  // 设置盘点状态
  if (row.profitNumber > 0) {
    row.standingBookType = '盘盈';
  } else if (row.profitNumber < 0) {
    row.standingBookType = '盘亏';
  } else {
    row.standingBookType = '无盈亏';
  }
};

// 计算盈亏金额和盘点状态
const calculateProfitMoney = (row: any) => {
  row.profitMoney = (Number(row.profitNumber) * Number(row.price)).toFixed(2);
  if (row.profitNumber > 0) {
    row.standingBookType = '盘盈';
  } else if (row.profitNumber < 0) {
    row.standingBookType = '盘亏';
  } else {
    row.standingBookType = '无盈亏';
  }
};

// 移除选中项
const removeSelected = (index?: number) => {
  if (index !== undefined) {
    formData.value.standingBookSub.splice(index, 1);
  } else {
    // 移除所有选中的项
    // 这里可以添加多选删除逻辑
  }
};

// 导入数据
const importData = () => {
  // 实现导入功能
  ElMessage.info('导入功能待实现');
};

// 计算合计数据

const totalStocktakingQuantity = computed(() => {
  return formData.value.standingBookSub.reduce((sum, item) => sum + (Number(item.standingBookNumber) || 0), 0);
});

const totalProfitQuantity = computed(() => {
  return formData.value.standingBookSub.reduce((sum, item) => {
    const profitLoss = Number(item.profitNumber) || 0;
    return sum + (profitLoss > 0 ? profitLoss : 0);
  }, 0);
});

const totalLossQuantity = computed(() => {
  return formData.value.standingBookSub.reduce((sum, item) => {
    const profitLoss = Number(item.profitNumber) || 0;
    return sum + (profitLoss < 0 ? Math.abs(profitLoss) : 0);
  }, 0);
});

const totalProfitAmount = computed(() => {
  return formData.value.standingBookSub.reduce((sum, item) => {
    const amount = Number(item.profitMoney) || 0;
    return sum + (amount > 0 ? amount : 0);
  }, 0);
});

const totalLossAmount = computed(() => {
  return formData.value.standingBookSub.reduce((sum, item) => {
    const amount = Number(item.profitMoney) || 0;
    return sum + (amount < 0 ? Math.abs(amount) : 0);
  }, 0);
});

const sub = '盘点单'
const Bianma = async () => {
  try {
    const res = await axios.post("api/app/dm_Encoderule/start-code?Formtypeid=" + sub);
    if (res.data.code === 200) {
      ysb.value = res.data.data; // 修正赋值操作符
      formData.value.standingBookOod = res.data.data; // 同时更新表单数据
      console.log('获取到的编码:', ysb.value);
      return res.data.data;
    }
  } catch (error) {
    console.error('获取编码失败:', error);
    ElMessage.error('获取编码失败');
    return null;
  }
}

const isEdit = ref(false); // 是否为编辑状态
const editOod = ref('');   // 当前编辑的盘点单号

const UpdateStanding = async (standingBookOod: any) => {
  isEdit.value = true;
  editOod.value = standingBookOod;
  try {
    const res = await axios.post('api/app/standing/show-stading?StandingBookOod=' + standingBookOod);
    console.log('API返回的原始数据:', res.data); // 调试用
    
    if (res.data.code === 200) {
      // 回显基础信息
      formData.value = {
        ...res.data.data,
        standingBookOod: res.data.data.standingBookOod || '',
        standingBookType: res.data.data.standingBookType || '',
        standingBookOpenDate: res.data.data.standingBookOpenDate || '',
        standingBookCloseDate: res.data.data.standingBookCloseDate || '',
        warehouseId: res.data.data.warehouseId || '',
        empid: res.data.data.empid || '',
        standingBookRemark: res.data.data.standingBookRemark || '',
      };
      
      // 处理明细数据 - 需要根据货品编号获取完整的货品信息
      if (res.data.data.standingBookSub && Array.isArray(res.data.data.standingBookSub)) {
        // 获取所有货品信息
        const itemIds = res.data.data.standingBookSub.map((item: any) => item.itemId || item.commodityId).filter(Boolean);
        
        if (itemIds.length > 0) {
          // 根据货品编号获取完整的货品信息
          const itemInfoRes = await axios.get('api/app/allot/item');
          const allItems = itemInfoRes.data.pageData || [];
          
          formData.value.standingBookSub = res.data.data.standingBookSub.map((item: any) => {
            const itemId = item.itemId || item.commodityId;
            // 查找对应的货品信息
            const itemInfo = allItems.find((info: any) => info.itemid === itemId);
            
            return {
              standingBookOod: standingBookOod,
              itemId: itemId,
              // 从货品信息中获取完整数据
              itemName: itemInfo ? itemInfo.itemname : '',
              itemSpec: itemInfo ? itemInfo.itemspec : '',
              unit: itemInfo ? itemInfo.unitid : '',
              itmeTypeName: itemInfo ? itemInfo.itmeTypeName : '',
              bookedInventory: itemInfo ? itemInfo.purchaseprice : 0,
              bookedAmount: itemInfo ? itemInfo.outboundprice : 0,
              // 保留原有的盘点相关数据
              storageLocationID: item.storageLocationID || item.storageLocationId || '',
              standingBookNumber: item.standingBookNumber || 0,
              profitNumber: item.profitNumber || 0,
              standingBookType: item.standingBookType || '无盈亏',
              price: item.price || 100,
              profitMoney: item.profitMoney || 0,
              standingBookRemark: item.standingBookRemark || ''
            };
          });
        } else {
          // 如果没有货品编号，直接使用原始数据
          formData.value.standingBookSub = res.data.data.standingBookSub.map((item: any) => ({
            standingBookOod: standingBookOod,
            itemId: item.itemId || item.commodityId || '',
            itemName: item.itemName || item.itemname || '',
            itemSpec: item.itemSpec || item.itemspec || '',
            unit: item.unit || item.unitid || '',
            itmeTypeName: item.itmeTypeName || item.itemTypeName || '',
            bookedInventory: item.bookedInventory || item.purchaseprice || 0,
            bookedAmount: item.bookedAmount || item.outboundprice || 0,
            storageLocationID: item.storageLocationID || item.storageLocationId || '',
            standingBookNumber: item.standingBookNumber || 0,
            profitNumber: item.profitNumber || 0,
            standingBookType: item.standingBookType || '无盈亏',
            price: item.price || 100,
            profitMoney: item.profitMoney || 0,
            standingBookRemark: item.standingBookRemark || ''
          }));
        }
      } else {
        // 如果没有明细数据，初始化为空数组
        formData.value.standingBookSub = [];
      }
      
      console.log('处理后的表单数据:', formData.value); // 调试用
      dialogFormVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取数据失败');
    }
  } catch (e) {
    console.error('获取数据失败:', e);
    ElMessage.error('获取数据失败');
  }
};

// 保存盘点单
const saveStocktaking = async () => {
  if (!formData.value.warehouseId) {
    ElMessage.warning('请选择仓库');
    return;
  }
  if (formData.value.standingBookSub.length === 0) {
    ElMessage.warning('请选择货品');
    return;
  }
  try {
    let code = formData.value.standingBookOod;
    // 新增时获取编码
    if (!isEdit.value) {
      code = await Bianma();
      if (!code) {
        ElMessage.error('获取盘点单号失败');
        return;
      }
      formData.value.standingBookOod = code;
      formData.value.standingBookSub.forEach(item => {
        item.standingBookOod = code;
      });
    }
    // 编辑时直接用已有的单号
    else {
      formData.value.standingBookSub.forEach(item => {
        item.standingBookOod = code;
      });
    }

    let res;
    if (isEdit.value) {
      // 编辑
      res = await axios.put('/api/app/standing/stading', formData.value);
    } else {
      // 新增
      res = await axios.post('/api/app/standing/latest-standing-book', formData.value);
    }
    if (res.data.code === 200) {
      ElMessage.success('保存成功');
      dialogFormVisible.value = false;
      Seach();
      // 重置表单
      formData.value = {
        "standingBookOod": "",
        "standingBookType": "",
        "standingBookOpenDate": "",
        "standingBookCloseDate": "",
        "warehouseId": "",
        "empid": "",
        "standingBookRemark": "",
        "standingBookSub": [
          {
            "standingBookOod": "",
            "itemId": "",
            "storageLocationID": "",
            "standingBookNumber": 0,
            "profitNumber": 0,
            "standingBookType": "",
            "price": 0,
            "profitMoney": 0,
            "standingBookRemark": ""
          }
        ]
      };
      isEdit.value = false;
      editOod.value = '';
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请重试');
  }
};



</script>



<style scoped>
.basic-info-card,
.detail-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.button-group {
  display: flex;
  align-items: center;
}

.flex-container {
  display: flex;
  align-items: center;
}

.flex-grow {
  flex: 1;
}

.setting-button {
  margin-left: 8px;
}

.summary-row {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  font-weight: bold;
}

.summary-row span {
  margin-right: 20px;
}

.full-width {
  width: 100%;
}
</style>